package com.mall.service.impl;

import com.mall.api.mall.param.SaveCartItemParam;
import com.mall.api.mall.param.UpdateCartItemParam;
import com.mall.common.Constants;
import com.mall.common.ZhaoTongMallException;
import com.mall.common.ServiceResultEnum;
import com.mall.api.mall.vo.ZhaoTongMallShoppingCartItemVO;
import com.mall.dao.ZhaoTongMallGoodsMapper;
import com.mall.dao.ZhaoTongMallShoppingCartItemMapper;
import com.mall.entity.ZhaoTongMallGoods;
import com.mall.entity.ZhaoTongMallShoppingCartItem;
import com.mall.service.ZhaoTongMallShoppingCartService;
import com.mall.util.BeanUtil;
import com.mall.util.PageQueryUtil;
import com.mall.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ZhaoTongMallShoppingCartServiceImpl implements ZhaoTongMallShoppingCartService {

    @Autowired
    private ZhaoTongMallShoppingCartItemMapper zhaoTongMallShoppingCartItemMapper;

    @Autowired
    private ZhaoTongMallGoodsMapper zhaoTongMallGoodsMapper;

    @Override
    public String saveZhaoTongMallCartItem(SaveCartItemParam saveCartItemParam, Long userId) {
        ZhaoTongMallShoppingCartItem temp = zhaoTongMallShoppingCartItemMapper.selectByUserIdAndGoodsId(userId, saveCartItemParam.getGoodsId());
        if (temp != null) {
            //已存在则修改该记录
            ZhaoTongMallException.fail(ServiceResultEnum.SHOPPING_CART_ITEM_EXIST_ERROR.getResult());
        }
        ZhaoTongMallGoods zhaoTongMallGoods = zhaoTongMallGoodsMapper.selectByPrimaryKey(saveCartItemParam.getGoodsId());
        //商品为空
        if (zhaoTongMallGoods == null) {
            return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
        }
        int totalItem = zhaoTongMallShoppingCartItemMapper.selectCountByUserId(userId);
        //超出单个商品的最大数量
        if (saveCartItemParam.getGoodsCount() < 1) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_NUMBER_ERROR.getResult();
        }
        //超出单个商品的最大数量
        if (saveCartItemParam.getGoodsCount() > Constants.SHOPPING_CART_ITEM_LIMIT_NUMBER) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
        }
        //超出最大数量
        if (totalItem > Constants.SHOPPING_CART_ITEM_TOTAL_NUMBER) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_TOTAL_NUMBER_ERROR.getResult();
        }
        ZhaoTongMallShoppingCartItem zhaoTongMallShoppingCartItem = new ZhaoTongMallShoppingCartItem();
        BeanUtil.copyProperties(saveCartItemParam, zhaoTongMallShoppingCartItem);
        zhaoTongMallShoppingCartItem.setUserId(userId);
        //保存记录
        if (zhaoTongMallShoppingCartItemMapper.insertSelective(zhaoTongMallShoppingCartItem) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String updateZhaoTongMallCartItem(UpdateCartItemParam updateCartItemParam, Long userId) {
        ZhaoTongMallShoppingCartItem zhaoTongMallShoppingCartItemUpdate = zhaoTongMallShoppingCartItemMapper.selectByPrimaryKey(updateCartItemParam.getCartItemId());
        if (zhaoTongMallShoppingCartItemUpdate == null) {
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        if (!zhaoTongMallShoppingCartItemUpdate.getUserId().equals(userId)) {
            ZhaoTongMallException.fail(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
        }
        //超出单个商品的最大数量
        if (updateCartItemParam.getGoodsCount() > Constants.SHOPPING_CART_ITEM_LIMIT_NUMBER) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
        }
        //当前登录账号的userId与待修改的cartItem中userId不同，返回错误
        if (!zhaoTongMallShoppingCartItemUpdate.getUserId().equals(userId)) {
            return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
        }
        //数值相同，则不执行数据操作
        if (updateCartItemParam.getGoodsCount().equals(zhaoTongMallShoppingCartItemUpdate.getGoodsCount())) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        zhaoTongMallShoppingCartItemUpdate.setGoodsCount(updateCartItemParam.getGoodsCount());
        zhaoTongMallShoppingCartItemUpdate.setUpdateTime(new Date());
        //修改记录
        if (zhaoTongMallShoppingCartItemMapper.updateByPrimaryKeySelective(zhaoTongMallShoppingCartItemUpdate) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public ZhaoTongMallShoppingCartItem getZhaoTongMallCartItemById(Long zhaoTongMallShoppingCartItemId) {
        ZhaoTongMallShoppingCartItem zhaoTongMallShoppingCartItem = zhaoTongMallShoppingCartItemMapper.selectByPrimaryKey(zhaoTongMallShoppingCartItemId);
        if (zhaoTongMallShoppingCartItem == null) {
            ZhaoTongMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        return zhaoTongMallShoppingCartItem;
    }

    @Override
    public Boolean deleteById(Long shoppingCartItemId, Long userId) {
        ZhaoTongMallShoppingCartItem zhaoTongMallShoppingCartItem = zhaoTongMallShoppingCartItemMapper.selectByPrimaryKey(shoppingCartItemId);
        if (zhaoTongMallShoppingCartItem == null) {
            return false;
        }
        //userId不同不能删除
        if (!userId.equals(zhaoTongMallShoppingCartItem.getUserId())) {
            return false;
        }
        return zhaoTongMallShoppingCartItemMapper.deleteByPrimaryKey(shoppingCartItemId) > 0;
    }

    @Override
    public List<ZhaoTongMallShoppingCartItemVO> getMyShoppingCartItems(Long zhaoTongMallUserId) {
        List<ZhaoTongMallShoppingCartItemVO> zhaoTongMallShoppingCartItemVOS = new ArrayList<>();
        List<ZhaoTongMallShoppingCartItem> zhaoTongMallShoppingCartItems = zhaoTongMallShoppingCartItemMapper.selectByUserId(zhaoTongMallUserId, Constants.SHOPPING_CART_ITEM_TOTAL_NUMBER);
        return getZhaoTongMallShoppingCartItemVOS(zhaoTongMallShoppingCartItemVOS, zhaoTongMallShoppingCartItems);
    }

    @Override
    public List<ZhaoTongMallShoppingCartItemVO> getCartItemsForSettle(List<Long> cartItemIds, Long zhaoTongMallUserId) {
        List<ZhaoTongMallShoppingCartItemVO> zhaoTongMallShoppingCartItemVOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(cartItemIds)) {
            ZhaoTongMallException.fail("购物项不能为空");
        }
        List<ZhaoTongMallShoppingCartItem> zhaoTongMallShoppingCartItems = zhaoTongMallShoppingCartItemMapper.selectByUserIdAndCartItemIds(zhaoTongMallUserId, cartItemIds);
        if (CollectionUtils.isEmpty(zhaoTongMallShoppingCartItems)) {
            ZhaoTongMallException.fail("购物项不能为空");
        }
        if (zhaoTongMallShoppingCartItems.size() != cartItemIds.size()) {
            ZhaoTongMallException.fail("参数异常");
        }
        return getZhaoTongMallShoppingCartItemVOS(zhaoTongMallShoppingCartItemVOS, zhaoTongMallShoppingCartItems);
    }

    /**
     * 数据转换
     *
     * @param zhaoTongMallShoppingCartItemVOS
     * @param zhaoTongMallShoppingCartItems
     * @return
     */
    private List<ZhaoTongMallShoppingCartItemVO> getZhaoTongMallShoppingCartItemVOS(List<ZhaoTongMallShoppingCartItemVO> zhaoTongMallShoppingCartItemVOS, List<ZhaoTongMallShoppingCartItem> zhaoTongMallShoppingCartItems) {
        if (!CollectionUtils.isEmpty(zhaoTongMallShoppingCartItems)) {
            //查询商品信息并做数据转换
            List<Long> zhaoTongMallGoodsIds = zhaoTongMallShoppingCartItems.stream().map(ZhaoTongMallShoppingCartItem::getGoodsId).collect(Collectors.toList());
            List<ZhaoTongMallGoods> zhaoTongMallGoods = zhaoTongMallGoodsMapper.selectByPrimaryKeys(zhaoTongMallGoodsIds);
            Map<Long, ZhaoTongMallGoods> zhaoTongMallGoodsMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(zhaoTongMallGoods)) {
                zhaoTongMallGoodsMap = zhaoTongMallGoods.stream().collect(Collectors.toMap(ZhaoTongMallGoods::getGoodsId, Function.identity(), (entity1, entity2) -> entity1));
            }
            for (ZhaoTongMallShoppingCartItem zhaoTongMallShoppingCartItem : zhaoTongMallShoppingCartItems) {
                ZhaoTongMallShoppingCartItemVO zhaoTongMallShoppingCartItemVO = new ZhaoTongMallShoppingCartItemVO();
                BeanUtil.copyProperties(zhaoTongMallShoppingCartItem, zhaoTongMallShoppingCartItemVO);
                if (zhaoTongMallGoodsMap.containsKey(zhaoTongMallShoppingCartItem.getGoodsId())) {
                    ZhaoTongMallGoods zhaoTongMallGoodsTemp = zhaoTongMallGoodsMap.get(zhaoTongMallShoppingCartItem.getGoodsId());
                    zhaoTongMallShoppingCartItemVO.setGoodsCoverImg(zhaoTongMallGoodsTemp.getGoodsCoverImg());
                    String goodsName = zhaoTongMallGoodsTemp.getGoodsName();
                    // 字符串过长导致文字超出的问题
                    if (goodsName.length() > 28) {
                        goodsName = goodsName.substring(0, 28) + "...";
                    }
                    zhaoTongMallShoppingCartItemVO.setGoodsName(goodsName);
                    zhaoTongMallShoppingCartItemVO.setSellingPrice(zhaoTongMallGoodsTemp.getSellingPrice());
                    zhaoTongMallShoppingCartItemVOS.add(zhaoTongMallShoppingCartItemVO);
                }
            }
        }
        return zhaoTongMallShoppingCartItemVOS;
    }

    @Override
    public PageResult getMyShoppingCartItems(PageQueryUtil pageUtil) {
        List<ZhaoTongMallShoppingCartItemVO> zhaoTongMallShoppingCartItemVOS = new ArrayList<>();
        List<ZhaoTongMallShoppingCartItem> zhaoTongMallShoppingCartItems = zhaoTongMallShoppingCartItemMapper.findMyZhaoTongMallCartItems(pageUtil);
        int total = zhaoTongMallShoppingCartItemMapper.getTotalMyZhaoTongMallCartItems(pageUtil);
        PageResult pageResult = new PageResult(getZhaoTongMallShoppingCartItemVOS(zhaoTongMallShoppingCartItemVOS, zhaoTongMallShoppingCartItems), total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }
}
